#include "lib_iic.h"

#define SCL_H gpio_set_level(IIC_SCL, IIC_UP)
#define SCL_L gpio_set_level(IIC_SCL, IIC_DOWN)
#define SDA_H gpio_set_level(IIC_SDA, IIC_UP)
#define SDA_L gpio_set_level(IIC_SDA, IIC_DOWN)

void I2C_GPIO_Init(void)
{
    gpio_config_t pGPIOConfig;
    pGPIOConfig.mode = GPIO_MODE_OUTPUT;
    pGPIOConfig.pin_bit_mask = GPIO_OUTPUT_PIN_SEL;
    pGPIOConfig.pull_down_en = 0;
    pGPIOConfig.pull_up_en = 0;
    pGPIOConfig.intr_type = GPIO_INTR_DISABLE;
    gpio_config(&pGPIOConfig);
}

static void I2C_Start(void)
{
    SCL_H;
    SDA_H;
    I2C_delay();
    SDA_L;
}

static void I2C_Stop(void)
{
    SCL_L;
    SDA_L;
    I2C_delay();
    SCL_H;
}

void I2C_SendByte(uint8_t SendByte)
{
    uint8_t i = 8;
    while (i--)
    {
        SCL_L;
        I2C_delay();
        if (SendByte & 0x80)
            SDA_H;
        else
            SDA_L;
        SendByte <<= 1;
        I2C_delay();
        SCL_H;
        I2C_delay();
    }
    SCL_L;
    I2C_delay();
    SDA_H;
    I2C_delay();
    SCL_H;
    I2C_delay();
}

void I2C_Sendstr(const uint8_t *pdata, uint8_t size)
{
    int temp = 0;
    I2C_Start();
    I2C_delay();
    I2C_SendByte(0X70);
    I2C_delay();
    for (temp = 0; temp < size; temp++)
    {
        I2C_SendByte(pdata[temp]);
        I2C_delay();
    }
    I2C_Stop();
}

void I2C_delay(void)
{   
    // 10 1.25us
    // 40 4us
    volatile uint16_t i = 50; /* 这里可以优化速度,经测试最低到5还能写入 */
    while (i)
    {
        i--;
    }
}

void i2c_test_task(void *arg)
{
    I2C_GPIO_Init();

    while (1)
    {
        SCL_H;
        I2C_delay();
        SCL_L;
        I2C_delay();
    }
}